package com.example.captcha1.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.captcha1.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    private final static long session_valid_timeout = 60*1000;
    @Autowired
    private CaptchaProperties captchaProperties;

    @RequestMapping("/get")
    public void getCaptcha(HttpSession session, HttpServletResponse response)throws IOException {
        long t1 = System.currentTimeMillis();
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        //设置返回值类型
        response.setContentType("image/jpeg");
        //禁止缓存
        response.setHeader("Progma","No-cache");
        //图形验证码写出，可以写出到文件，也可以写出到流
        lineCaptcha.write(response.getOutputStream());
        String code = lineCaptcha.getCode();
        //存储session
        session.setAttribute(captchaProperties.getSession().getKey(), code);
        session.setAttribute(captchaProperties.getSession().getDate(), new Date());

        long t2 = System.currentTimeMillis();
        System.out.println("执行时间: " + (t2 - t1));
    }

    @RequestMapping("/check")
    public Boolean check(String inputCode, HttpSession session) {
        //验证码生成的内容和用户输入的内容进行比较
        if(!StringUtils.hasLength(inputCode)) {
            return false;
        }
        //从Session中获取信息
        String savedCode = (String) session.getAttribute(captchaProperties.getSession().getKey());
        Date saveDate = (Date) session.getAttribute(captchaProperties.getSession().getDate());

        if(inputCode.equalsIgnoreCase(savedCode)) {
            //验证是否过期
            if(saveDate != null && System.currentTimeMillis() - saveDate.getTime() < session_valid_timeout) {
                return true;
            }
        }

        return false;
    }

}
